package com.splant.android.smart.CommunicationLevel;



import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Created by Administrator on 2015/8/29.
 */
public class P2PUDPClientB {

    private final String clientTag="ClientB";
    private SocketAddress targetServer;
    private DatagramSocket client;
    private int bufLength=1024;//缓存大小
    public InetAddress clientA_Address;//客户端A的IP地址
    public int clientA_Port;//客户端A的端口

    public P2PUDPClientB(String host, int port) {
        try
        {
            client = new DatagramSocket();
            targetServer=new InetSocketAddress(host,port);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //登录服务器
    public boolean loginServerAndConnectClientA()
    {
        boolean tf=false;
        try
        {
            byte[] sendbuf =clientTag.getBytes();
            DatagramPacket pack = new DatagramPacket(sendbuf, sendbuf.length, targetServer);
            client.send(pack);

            //接收server的回复内容
            byte[] buf = new byte[bufLength];
            DatagramPacket recpack = new DatagramPacket(buf, buf.length);
            client.receive(recpack);

            //处理server回复的内容，然后向内容中的地址与端口发起请求（打洞）
            String receiveMessage = new String(recpack.getData(), 0, recpack.getLength());
            String[] params = receiveMessage.split(",");
            String host = params[0].substring(5);
            String port = params[1].substring(5);

            clientA_Address=InetAddress.getByName(host);
            clientA_Port=Integer.parseInt(port);

           tf=true;
        }
        catch (Exception e)
        {

        }
        return tf;
    }

    //向UPDClientA发起请求(在NAT上打孔)
    public boolean sendMessageToClientA(InetAddress inetAddress,int port,byte[] sendbuf) {
        boolean tf=false;
        try
        {

            DatagramPacket pack = new DatagramPacket(sendbuf, sendbuf.length, inetAddress,port);
            client.send(pack);

            tf=true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return tf;
    }

    //收到UDPClientA的回复内容，穿透已完成
    public  byte[] receiveFromClientA()
    {
        byte[] recBytes=null;
        try
        {
                //将接收到的内容打印
                byte[] buf = new byte[1024];
                DatagramPacket recpack = new DatagramPacket(buf, buf.length);
                client.receive(recpack);
                recBytes=recpack.getData();
               // String receiveMessage = new String(recpack.getData(), 0, recpack.getLength());

                //记得重新收地址与端口，然后在以新地址发送内容到UPDClientA,就这样互发就可以了。
                clientA_Port = recpack.getPort();
                clientA_Address = recpack.getAddress();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return recBytes;
    }

}
